
package com.pp.admin.common.server;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;

public class PersistenceManagerFactory {
	
	protected static final javax.jdo.PersistenceManagerFactory	PMF					= JDOHelper.getPersistenceManagerFactory( "transactions-optional" );
	
	private static ThreadLocal<PersistenceManager>				pm					= new ThreadLocal<PersistenceManager>();
	
	private static ThreadLocal<Integer>							pmReferenceCount	= new ThreadLocal<Integer>();
	
	public static synchronized PersistenceManager getPersistenceManager() {

		PersistenceManager pmResp = pm.get();
		if ( pmResp == null ) {
			pmResp = PMF.getPersistenceManager();
			pm.set( pmResp );
			pmReferenceCount.set( 1 );
		} else {
			Integer count = pmReferenceCount.get();
			count++;
			pmReferenceCount.set( count );
		}
		System.out.println( "getter => " + pmReferenceCount.get() );
		return pmResp;
	}
	
	public static synchronized void closePersistenceManager() {

		Integer count = pmReferenceCount.get();
		count--;
		pmReferenceCount.set( count );
		if ( count == 0 ) {
			pm.get().close();
			pmReferenceCount.set( null );
			pm.set( null );
		}
		System.out.println( "Closes =>" + pmReferenceCount.get() );
	}
}
